{extend name="app/shop/view/base.html"/}
{block name="resources"}
<link rel="stylesheet" type="text/css" href="SHOP_CSS/picture_manager.css" />
<style>
    .album-box .album-img-box{display: flex;flex-wrap: wrap;}
    .album-box .album-content{margin-top: 10px;}
    .album-box .album-img-box li{margin: 0 13px 20px;position: relative;width: 290px;height: 187.5px;cursor: pointer;border: 1px solid #ccc;padding: 2px;}
    .album-box .album-img-box li.selected{border-color: var(--base-color);}
    .album-box .album-img-box li.selected .iconfont{color: var(--base-color);}
    .album-box .album-img-box li .iconfont{position: absolute;bottom: 0;right: 0;font-size: 30px;color: transparent;}
    .album-box .album-img-box li .album-pic{width: 100%;height: 100%;background-size: 100% 100%;background-repeat: no-repeat;background-position: center;}
    .album-box .album-img-box li .album-img-operation{position: absolute;top: 0;right: 0;bottom: 0;left: 0;background-color: rgba(0, 0, 0, .5);display: none;align-items: center;justify-content: center;color: #fff;}
    .album-box .album-img-box li .album-img-operation a{margin: 0 12px;color: #fff;font-size: 14px;}
    .multuple-list{max-height: 275px; height: auto;}
    .upload-attention{margin-left: 75px;}
    .multuple-list-box{display: flex;flex-direction: column;height: 100%;}
    .multuple-list-box .form-row{margin-top: auto;}
    .album-box .album-img-box li:hover .album-img-operation{display: flex;}
    .album-foot-operation{margin-top: auto;display: flex;justify-content: flex-end;padding: 0 25px;}
    .preview-img .layui-layer-content{padding: 0;}
    .album-content .album-img-box li:nth-child(7n){margin-right: 13px;}
</style>
{/block}
{block name="main"}
<!-- 清理网站缓存 start-->
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache, no-store">
<meta http-equiv="expires" content="0">
<!-- 清理网站缓存 end-->

<!-- 搜索框 -->
<div class="single-filter-box top">
    <button class="layui-btn" onclick="uploadImg()">添加素材</button>
</div>
<div class="album-box">
    <div class="album-content">
        <ul class="album-img-box"></ul>
        <div class="album-foot-operation">
            <div id="paged" class="page"></div>
        </div>
    </div>
    <!-- 存储图片路径 -->
    <input type="hidden" id="hidden_image_path">
</div>
{/block}
{block name="script"}
<!-- 相册展示 -->
<script type="text/html" id="list_html">
    {{# layui.each(d.list,function(index, item){ }}
    <li class="img layui-show">
        <div class="album-pic" layer-src="{{ ns.img(item.media_path + '?time=' + parseInt(new Date().getTime()/1000)) }}" style="background-image:url({{ ns.img(item.media_path + '?time=' + parseInt(new Date().getTime()/1000)) }})"></div>
        <div class="album-img-operation">
            <a href="javascript:;" data-id="{{item.media_id}}" onclick="previewFile('{{item.media_path}}','{{item.media_spec}}')">预览</a> |
            <a href="javascript:;" data-id="{{item.media_id}}" onclick="modifyFile(this)">替换</a> |
            <a href="javascript:;" class="delete-pic" data-id="{{item.media_id}}" onclick="deleteImg(this)">删除</a>
        </div>
        <i class="iconfont iconxuanzhong"></i>
    </li>
    {{# }) }}
</script>

<!-- 多图上传 -->
<script type="text/html" id="multuple_html">
    <div class="layui-form multuple-list-box">
        <div class="layui-form-item">
            <label class="layui-form-label sm">本地图片</label>
            <ul class="layui-input-block multuple-list">
                <li class="multuple-list-img" id="ImgUpload">
                    <span class="bg-color">+</span>
                    <span>点击添加图片</span>
                </li>
            </ul>
            <p class="upload-attention">请上传320*220素材图片</p>
        </div>
        <div class="form-row sm">
            <button class="layui-btn layui-btn-disabled" disabled="disabled" onclick="submitOne()"  id="chooseListAction">提交</button>
            <button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
        </div>
    </div>
</script>

<!-- 替换图片 -->
<script type="text/html" id="modify_file_html">
    <div class="layui-form multuple-list-box">
        <div class="layui-form-item">
            <label class="layui-form-label sm">本地图片</label>
            <ul class="layui-input-block multuple-list">
                <li class="multuple-list-img" id="modifyFile">
                    <span class="bg-color">+</span>
                    <span>点击添加图片</span>
                </li>
            </ul>
            <p class="upload-attention">请上传320*220素材图片</p>
        </div>
        <div class="form-row sm">
            <button class="layui-btn layui-btn-disabled" disabled="disabled" id="modifyFileAction">提交</button>
            <button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
        </div>
    </div>
</script>

<script>
    var form, upload, laytpl, layer, laypage, layer_one,element,
        picture_arr = [],
        initIdent= true,
        limit = 10,
        album_list_count = 0;
    var repeat_flag = false;

    $(function() {
        layui.use(['form', 'laytpl', 'laypage', 'layer', 'upload', 'element'], function () {
            form = layui.form;
            laytpl = layui.laytpl;
            laypage = layui.laypage;
            element = layui.element;
            layer = layui.layer;
            upload = layui.upload;

            init(); //初始化数据
            form.render();
            element.init();
        });
    });

    /**
     * 图片加载
     */
    function getFileAlbumList(page, limit) {
        $.ajax({
            url: ns.url("giftcard://shop/media/lists"),
            type: "POST",
            dataType: "JSON",
            async: false,
            data: {
                pic_name: $(".album-img-sreach").val(),
                page_size:limit,
                page
            },
            success: function(res) {
                res.data.status = $('.album-content-title .edit').attr('data-status');
                laytpl($("#list_html").html()).render(res.data, function(html) {
                    $(".album-img-box").html(html);
                    loadImgMagnify();
                });
                if(initIdent){
                    album_list_count = res.data.list.length;
                    $(".default-group .num").text(album_list_count);
                    initIdent = false;
                }
                $("#paged").empty();
                if (res.data.count > 0) {
                    //调用分页
                    laypage.render({
                        elem: "paged",
                        count: res.data.count,
                        curr: page, //当前页
                        limit: limit,
                        jump: function(obj, first) {
                            if (!first) {
                                getFileAlbumList(obj.curr, obj.limit);
                            }
                            form.render('checkbox');
                        }
                    })
                }
            }
        })
    }

    // 图片替换
    function modifyFile(data) {
        laytpl($("#modify_file_html").html()).render({}, function(html) {
            layer_one = layer.open({
                type: 1,
                area: ['580px', '500px'],
                title: '替换图片',
                content: html,
                cancel: function() {
                    $("#modifyFileAction").removeClass("bg-color").addClass("layui-btn-disabled").attr("disabled", "disabled");
                },
                success: function(res) {
                    //上传图片
                    upload.render({
                        elem: '#modifyFile',
                        url: ns.url("giftcard://shop/media/modifyFile"),
                        data: {
                            media_id: $(data).attr('data-id')
                        },
                        multiple: true,
                        auto: false,
                        bindAction: '#modifyFileAction',
                        choose: function(obj) {
                            //将每次选择的文件追加到文件队列
                            var files = this.files = obj.pushFile();
                            //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                            obj.preview(function(index, file, result) {
                                //追加预览图片
                                var html = '';
                                html += '<li class="multuple-list-img upload-wrap" index="' + index + '">';
                                html += '<img src="' + result + '" alt="' + file.name + '">';
                                html += '<span class="upload-close-modal"  id="upload_img_' + index + '">×</span>';
                                html += '<div class="upload-image-curtain">50%</div>';
                                html += '<div class="tips"></div>';
                                html += '</li>';
                                $(".multuple-list").prepend(html);

                                //删除预览图片
                                $("#upload_img_" + index).bind("click", function() {
                                    delete files[index];
                                    delete picture_arr[index]; //删除所选队列
                                    $(this).parent('.upload-wrap').remove();

                                    // uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选

                                    //禁止点击
                                    if ($(".multuple-list li").length <= 1) {
                                        $("#modifyFileAction").removeClass("bg-color").addClass("layui-btn-disabled").attr("disabled", "disabled");
                                        //未选择图片时，显示添加按钮
                                        $("#modifyFile").show();
                                    }

                                });

                                //禁止点击
                                if ($(".multuple-list li").length > 1) {
                                    $("#modifyFileAction").addClass("bg-color").removeClass("layui-btn-disabled").removeAttr("disabled");
                                    //隐藏添加按钮，仅替换一张图片
                                    $("#modifyFile").hide();
                                }
                            });
                        },
                        done: function(res, index) {
                            picture_arr.push(res.data);
                            var image_box = $(".upload-wrap[index='" + index + "']").parent().find(".upload-image-curtain");
                            var image_tips = $(".upload-wrap[index='" + index + "']").parent().find(".tips");
                            image_box.text("50%");
                            image_box.show();
                            if (res.code >= 0) {
                                setTimeout(function() {
                                    image_box.text("100%");
                                }, 500);
                                setTimeout(function() {
                                    getFileAlbumList(1, limit);
                                    layer.close(layer_one);
                                }, 1000);
                                return delete this.files[index]; //删除文件队列已经上传成功的文件
                            } else {
                                setTimeout(function() {
                                    image_box.text("上传失败");
                                    image_tips.text(res.message);
                                    layer.close(layer_one);
                                }, 500);

                            }
                        }
                    });

                }
            })
        });

    }

    // 预览图片
    function previewFile(path, spec){
        spec = spec.split("*");
        layer.open({
            type:1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            area: [spec[0]+'px', spec[1]+'px'], //宽高
            content: "<img src=" + ns.img(path) + " />",
            skin: 'preview-img'
        });   
    }

    /**
     * 初始化数据
     */
    function init() {
        getFileAlbumList(1, limit); //图片加载
    }

    /**
     * 多图上传
     */
    function uploadImg() {
        var imageArray=1;
        laytpl($("#multuple_html").html()).render({}, function(html) {
            layer_one = layer.open({
                type: 1,
                area: ['580px', '430px'],
                title: '本地上传',
                content: html,
                cancel: function() {
                    $("#chooseListAction").removeClass("bg-color").addClass("layui-btn-disabled").attr("disabled", "disabled");
                },
                success: function(res) {
                    //上传图片
                    upload.render({
                        elem: '#ImgUpload',
                        url: ns.url("giftcard://shop/media/upload"),
                        data: {
                            is_thumb:1,
                        },
                        multiple: true,
                        auto: false,
                        bindAction: '#chooseListAction',
                        choose: function(obj) {
                            imageArray=1;
                            //将每次选择的文件追加到文件队列
                            var files = this.files = obj.pushFile();
                            //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                            obj.preview(function(index, file, result) {
                                this.num=index;
                                //追加预览图片
                                var html = '';
                                html += '<li class="multuple-list-img upload-wrap" index="' + index + '">';
                                html += '<img class="multuple-list-image" src="' + result + '" alt="' + file.name + '">';
                                html += '<span class="upload-close-modal"  id="upload_img_' + index + '">×</span>';
                                html += '<div class="upload-image-curtain">50%</div>';
                                html += '<div class="tips"></div>';
                                html += '</li>';
                                $(".multuple-list").prepend(html);
                                //删除预览图片
                                $("#upload_img_" + index).bind("click", function() {
                                    delete files[index];
                                    delete picture_arr[index]; //删除所选队列
                                    $(this).parent('.upload-wrap').remove();
                                    // uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                                    //禁止点击
                                    if ($(".multuple-list li").length <= 1) {
                                        $("#chooseListAction").removeClass("bg-color").addClass("layui-btn-disabled").attr("disabled", "disabled");
                                    }
                                });
                                //开启点击
                                if ($(".multuple-list li").length > 1) {
                                    $("#chooseListAction").addClass("bg-color").removeClass("layui-btn-disabled").removeAttr("disabled");
                                }

                            });
                        },
                        done: function(res,index) {
                            let data=$('.multuple-list-image');
                            // 禁止点击
                            picture_arr.push(res.data);
                            var image_box = $(".upload-wrap[index='" + index + "']").parent().find(".upload-image-curtain");
                            var image_tips = $(".upload-wrap[index='" + index + "']").parent().find(".tips");
                            image_box.text("上传汇总");
                            image_box.text("50%");
                            image_box.show();
                            if (res.code >= 0) {
                                setTimeout(function() {
                                    image_box.text("100%");
                                }, 500);
                                setTimeout(function() {
                                    getFileAlbumList(1, limit);
                                    layer.close(layer_one)
                                }, 1000);
                                return delete this.files[index]; //删除文件队列已经上传成功的文件
                            } else {
                                setTimeout(function() {
                                    image_box.text("上传失败");
                                    image_tips.text(res.message);
                                    layer.msg(res.message);
                                }, 500);
                            }
                            if(imageArray==data.length){
                                $("#chooseListAction").addClass("bg-color").removeClass("layui-btn-disabled").removeAttr("disabled");
                                imageArray=1;
                                return false
                            }
                            imageArray++
                        }
                    });
                }
            })
        });
    }

    // 上传图片是禁止操作
    function submitOne(){
        $("#chooseListAction").removeClass("bg-color").addClass("layui-btn-disabled").attr("disabled","disabled");
        $(".upload-image-curtain").css('display','block').text('等待中')
    }

    function deleteImg(data) {
        var flag_delete_img = false;
        var media_id = $(data).attr("data-id");
        if(!media_id){
            layer.msg("请选择图片再进行操作");
            return false;
        }
        var url = ns.url("giftcard://shop/media/delete");
        layer.confirm('删除图片会连本地存储或云存储的图片也删掉,请谨慎操作！', {
            btn: ['确定', '取消']
        }, function() {
            if (flag_delete_img) return;
            flag_delete_img = true;
            $.ajax({
                type: "POST",
                async: true,
                url,
                data: {
                    media_id: media_id
                },
                dataType: "JSON",
                success: function(data) {
                    flag_delete_img = false;
                    layer.msg(data.message);
                    if (data.code == 0) {
                        getFileAlbumList(1, limit);
                        layer.closeAll('page');
                    }
                }
            });
        }, function() {
            layer.close();
        });
    }
</script>
{/block}